﻿using System;
using System.Web.Mail;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using MLY;
using MLY.Dal;
using MLY.Bll;
using System.IO;

namespace MLY.LTR
{

    public partial class MlyLtrMaster : System.Web.UI.MasterPage
    {
        protected override void OnError(EventArgs e)
        {
            
            HttpContext ctx = HttpContext.Current;
            Exception exception = ctx.Server.GetLastError();
            string errorInfo =
               "<br>Source: " + exception.Source +
               "<br>Message: " + exception.Message +
               "<br>Stack trace: " + exception.StackTrace;
            Session["error"] = errorInfo;

            string requestUrl = ctx.Request.Url.ToString();
            string url = string.Format(@"/customErrors.aspx?ReturnTo={0}", requestUrl);
            ctx.Response.RedirectTo(url);

            // --------------------------------------------------
            // To let the page finish running we clear the error
            // --------------------------------------------------
            ctx.Server.ClearError();
            base.OnError(e);
        }

        protected void btnMsg_Click(object sender, EventArgs e)
        {
            Response.RedirectTo("~/LTR/Messages.aspx");
        }

        private void AddHeaderStyle()
        {
            //string url = Request.Url.ToString().ToLower();
            //if (url.IndexOf("gridbasepage") != -1)
            //    MainDivPanel.CssClass = "mainContentGrid";
            //else
            //    MainDivPanel.CssClass = "mainContent";

            //if (url.IndexOf("login") != -1 || url.IndexOf("default") != -1)
            //  Panel1.CssClass = "midPanelImage";
            //else
            //  Panel1.CssClass = "midPanel";
            //if (url.IndexOf("login") != -1 || url.IndexOf("default") != -1)
            //{
            //    MainDivPanel.CssClass = "niceBackground";
            //}
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Page.Header.DataBind();
                //ddlOrganization.SelectedValue = SelectedOrganizationID();
                //AddHeaderStyle();

                if ((clsUser.CurrentUserRoleId < 0) &&
                    (Page.Request.Url.ToString().IndexOf("/Login.aspx") < 0) &&
                    Page.Request.Url.ToString().IndexOf("contractorSearch2.aspx") < 0)
                {
                    Response.RedirectTo("/LTR/Login.aspx?ReturnTo=" + Request.Url.ToString());
                }
                else
                {
                    // removed - redundand and buggy. Using session parameters insead
                    //if (Utils.currOrg.Data != null)
                    //    this.lblName.Text = Utils.currOrg.Data.OrganizationName;
                    ////if (Session["CompanyName"] != null)
                    ////    this.lblName.Text = Session["CompanyName"].ToString();
                    if (Session["OrganizationId"] != null)
                        LastUploadLabel.Text = Dictionary.Translate("Master.LastUpload") + ": " +
                                               UploadLog.getLastUpload(int.Parse(Session["OrganizationId"].ToString()));

                    // getting last login
                    string LastLogin = Utils.GetPreviousLogin();
                    if (LastLogin.Length > 0)
                    {
                        LastLoginLabel.Text = Dictionary.Translate("Master.LastLogin") + ": " + LastLogin;
                    }

                    this.lblOrganization.Text = Bll.clsUser.CurrentUserCompanyName;
                    OrgNameLiteral.Text = Bll.clsUser.CurrentUserCompanyName;
                }

                ////if (clsUser.CurrentUserRoleId >= (int)clsUser.enumRoleId.Role60_Admin)
                ////{
                ////    this.lblOrganization.Visible = false;
                ////    this.ddlOrganization.Visible = true;
                ////}
                ////else
                ////{
                ////    this.lblOrganization.Visible = true;
                ////    this.ddlOrganization.Visible = false;
                ////}

                


                //if (Utils.currUser.IsExist)
                //    this.currUserLbl.Text = "  hello, " + Utils.currUser.Data.FullName;
                //else
                //{
                //    this.currUserLbl.Text = "";
                //    this.lblOrganization.Visible = false;
                //    this.lblName.Text = "";
                //}
                ////if (Utils.currUser.Data != null)
                ////    userNameLbl.Text = " Hello " + Utils.currUser.Data.FullName;
                CreateMenus();
                LoadDemoText();
            }
            if (SessParam.Culture == "he")
            {
                cssLiteral.Text = Environment.NewLine + "<link type=\"text/css\" rel=\"stylesheet\" href=\"/Style/Rtl_Stylesheet_v9.css\" />" + Environment.NewLine;
                CSCovercssLiteral.Text = Environment.NewLine + "<link type=\"text/css\" rel=\"stylesheet\" href=\"/Style/CSCover_RTL_v9.css\" />" + Environment.NewLine;
                HebrewLinkButton.CssClass = "SC_FlagsPicPosition SC_FloatLeft SC_LanguageLink bld";
            }
            else
            {
                cssLiteral.Text = Environment.NewLine + "<link type=\"text/css\" rel=\"stylesheet\" href=\"/Style/Ltr_Stylesheet_v9.css\" />" + Environment.NewLine;
                CSCovercssLiteral.Text = Environment.NewLine + "<link type=\"text/css\" rel=\"stylesheet\" href=\"/Style/CSCover_LTR_v9.css\" />" + Environment.NewLine;
                EnglishLinkButton.CssClass = "SC_FlagsPicPosition SC_FloatLeft SC_LanguageLink bld";
            }
        }

        protected void LoadDemoText()
        {
            // For now the demo is removed.

            //if ((Session["UserId"] != null) && ((Session["UserId"].ToString() == "39") || ((Session["UserId"].ToString() == "44"))))
            //{
            //    DemoLabel.Text = Demo.Text((string)Session["DemoStage"], (string)Session["DemoSubStage"], "DemoLabel");
                
            //    if (((string)Session["DemoStage"] == "Done") &&
            //        ((string)Session["DemoSubStage"] != "1"))
            //    {
            //        DemoPanel.Visible = false;
            //    }
            //    if (((string)Session["DemoStage"] == "Done") &&
            //        ((string)Session["DemoSubStage"] == "1"))
            //    {
            //        Demo.MoveToNextDemoSubStage();
            //        DeleteYoav2Alerts();
            //    }
            //    if ((string)Session["DemoStage"] == "Alerts" &&
            //        ((string)Session["DemoSubStage"] == "5"))
            //    {
            //        Demo.MoveToNextDemoSubStage();
            //    }

            //    if ((string)Session["DemoStage"] == "Hebrew")
            //    {
            //        Demo.MoveToNextDemoStage();
            //    }                
            //}
            //else
                DemoPanel.Visible = false;
        }

        private void DeleteYoav2Alerts()
        {
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MLYConnectionString"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("DeleteDemoAlerts", conn);
                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
                catch { }
            }
        }

        protected void btnLanguageHe_Click(object sender, EventArgs e)
        {
            //Session["Culture"] = "he";
            SessParam.Culture = "he";
            Response.AddHeader("refresh", "0");
        }

        protected void btnLanguageEng_Click(object sender, EventArgs e)
        {
            //Session["Culture"] = "en";
            SessParam.Culture = "en";
            Response.AddHeader("refresh", "0");
        }

        protected void btnLanguageMLY_Click(object sender, ImageClickEventArgs e)
        {
            SessParam.Culture = "dict";
            Response.AddHeader("refresh", "0");
        }

        //protected void ddlOrganization_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    Session["OrganizationId"] = Int32.Parse(this.ddlOrganization.SelectedValue);
        //    ViewState["currSelectionId"] = Int32.Parse(this.ddlOrganization.SelectedValue);
        //    if (ddlOrganization.SelectedValue != "0")
        //    {
        //        Session["OrganizationId"] = Int32.Parse(ViewState["currSelectionId"].ToString());
        //        ddlOrganization.SelectedValue = Session["OrganizationId"].ToString();
        //    }
        //    else
        //        Session["OrganizationId"] = -1;
        //}

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            lqKbmDataContext db = new lqKbmDataContext();
            TableUser currUser = (from p in db.TableUsers
                                  where p.UserId.ToString() == Session["UserId"].ToString()
                                  select p).FirstOrDefault();
            Utils.mlySendMail("User " + currUser.FullName + " wishes to make contact - he is on phone num:" + currUser.Phone,
                              Utils.AppSettings("Email"), "", "", "", false, null);
        }

        private string SelectedOrganizationID()
        {
            string selected = null;
            if (orgIdHidden.Value != "")
                selected = orgIdHidden.Value;
            else
            {
                if (Session["OrganizationId"] != null)
                    selected = Session["OrganizationId"].ToString();
            }
            List<TableOrganization> organizationsPlusSelect = clsOrganization.GetOrganizationsPlusSelect();
            foreach (TableOrganization tableOrganization in organizationsPlusSelect)
            {
                if (tableOrganization.OrganizationId.ToString().Equals(selected))
                {
                    return selected;
                }
            }
            selected = organizationsPlusSelect[0].OrganizationId.ToString();
            return selected;
        }

        protected void KeepAlive(object sender, EventArgs e)
        {
            /// session time out workaround
            try
            {
                int NumTicks = int.Parse(NumTicksHF.Value);
                if (NumTicks < 10)
                {
                    NumTicks++;
                    NumTicksHF.Value = NumTicks.ToString();
                    using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MLYConnectionString"].ConnectionString))
                    {
                        SqlCommand cmd = new SqlCommand("SELECT GetDate()", conn);
                        cmd.CommandType = CommandType.Text;

                        try
                        {
                            conn.Open();
                            cmd.ExecuteNonQuery();
                        }
                        catch { }
                    }

                }
                else
                    KeepAliveTimer.Interval = 99999999;
            }
            catch { }
        }
        protected void DemoSwitchToNextStep(object sender, EventArgs e)
        {
            Demo.MoveToNextDemoStage();
            DemoLabel.Text = Demo.Text((string)Session["DemoStage"], (string)Session["DemoSubStage"], "DemoLabel");
            Menu21.LoadDemoStyle();
        }

        private void CreateMenus()
        {
            if (Utils.currUser.IsExist)
            {
                TopMenuTitle.Text = "Hello, " + Utils.currUser.Data.FullName;
            }

            //if (Utils.currUser.IsExist)
            //{ 
            //    SC_TopMenu.Items[0].Text = "Hello, " + Utils.currUser.Data.FullName;
            //    if (Session["CompanyName"] != null)
            //    {
            //        MenuItem cName = new MenuItem(Session["CompanyName"].ToString());
            //        SC_TopMenu.Items[0].ChildItems.Add(cName);
            //    }
            //    if (Session["OrganizationId"] != null)
            //    {
            //        MenuItem oName = new MenuItem(Session["OrganizationId"].ToString());
            //        SC_TopMenu.Items[0].ChildItems.Add(oName);
            //    }
            //    string LastLogin = Utils.GetPreviousLogin();
            //    if (LastLogin.Length > 0)
            //    {
            //        MenuItem lastLogin = new MenuItem(Dictionary.Translate("Master.LastLogin") + ": " + LastLogin);
            //        SC_TopMenu.Items[0].ChildItems.Add(lastLogin);
            //    }
                
            //}
        }

        protected bool UserLoggedIn()
        {
            return (SessParam.UserId != -1);
        }

        protected void Logout_Click(object sender, EventArgs e)
        {
            Utils.logOff();
            
        }

        protected void SearchSupplier(object sender, EventArgs e)
        {
            string Suppliername = SupplierSearchTextBox.Text;
            if (Suppliername.Length > 0)
                Response.Redirect("~/LTR/contractorSearch2.aspx?Name=" + Suppliername);
            else
                Response.Redirect("~/LTR/contractorSearch2.aspx");
        }

        protected void ChangeToContructorView(object sender, EventArgs e)
        {
            SessParam.IsClient = false;
            Response.Redirect("~/LTR/default.aspx");
        }

        protected void ChangeToClientView(object sender, EventArgs e)
        {
            SessParam.IsClient = true;
            Response.Redirect("~/LTR/default.aspx");
        }

        
        //protected void DemoSwitchToNextStep(object sender, EventArgs e)
        //{
        //    if (((string)Session["DemoCode"] == "1") ||
        //        ((string)Session["DemoCode"] == "2") ||
        //        ((string)Session["DemoCode"] == "3") ||
        //        ((string)Session["DemoCode"] == "4"))
        //    {
        //        Session["DemoCode"] = "4.5";
        //        Menu21.LoadDemoStyle();
        //    }
        //    else if (((string)Session["DemoCode"] == "4.5") ||
        //             ((string)Session["DemoCode"] == "5") ||
        //             ((string)Session["DemoCode"] == "6"))
        //    {
        //        Session["DemoCode"] = "6.1";
        //        Menu21.LoadDemoStyle();
        //    }
        //    else if (((string)Session["DemoCode"] == "6.1") ||
        //             ((string)Session["DemoCode"] == "7") ||
        //             ((string)Session["DemoCode"] == "8") ||
        //             ((string)Session["DemoCode"] == "8.1") ||
        //             ((string)Session["DemoCode"] == "9") ||
        //             ((string)Session["DemoCode"] == "10") ||
        //             ((string)Session["DemoCode"] == "11"))
        //    {
        //        Session["DemoCode"] = "12";
        //        Menu21.LoadDemoStyle();
        //    }
        //    else if (((string)Session["DemoCode"] == "12") ||
        //             ((string)Session["DemoCode"] == "12.1"))
        //    {
        //        Session["DemoCode"] = "13";
        //        Menu21.LoadDemoStyle();
        //    }
        //    else if ((string)Session["DemoCode"] == "13")
        //    {
        //        Session["DemoCode"] = "13.1";
        //        Menu21.LoadDemoStyle();
        //    }
        //    else if ((string)Session["DemoCode"] == "13.1")
        //    {
        //        Session["DemoCode"] = "998";
        //        Menu21.LoadDemoStyle();
        //    }
        //    else if ((string)Session["DemoCode"] == "998")
        //    {
        //        Session["DemoCode"] = "999";
        //        Menu21.LoadDemoStyle();
        //    }

        //    LoadDemoText();
        //}
    }
}
